package cn.owen.config;

import java.util.Collection;

import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CustomizedModularRealmAuthenticator extends ModularRealmAuthenticator {

	@Override
	protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		//断言realm配置不能为空
		assertRealmsConfigured();
		CustomizedToken customizedToken = (CustomizedToken) authenticationToken;
		String loginType = customizedToken.getLoginType();
		Collection<Realm> realms = getRealms();
		for (Realm realm : realms) {
			if (realm.getName().contains(loginType)) {
				return doSingleRealmAuthentication(realm, customizedToken);
			}
		}
		return super.doAuthenticate(authenticationToken);
	}

	@Override
	protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
		if (!realm.supports(token)) {
			throw new ShiroException("token错误");
		}
		AuthenticationInfo info = null;
		try {
			info = realm.getAuthenticationInfo(token);
			if (null == info) {
				throw new ShiroException("token不存在");
			}
		} catch (AuthenticationException e) {
			throw new ShiroException("用户名或密码错误");
		}
		return info;
	}
	
	
}
